"""
Based on original snippet by rafacdb (http://www.djangosnippets.org/snippets/955/)
"""

import os
import Image
from django.template import Library
from django.conf import settings

import logging
log = logging.getLogger('docket.templatetags.thumbnail')

register = Library()

def thumbnail(mediafile, size='104x104'):
    # defining the size
    x, y = [int(x) for x in size.split('x')]
    
    original_height = mediafile.get_image_height()
    original_width = mediafile.get_image_width()
    
    # Fit the image into the maximum size given.
    if original_height > original_width and original_height > y:
        ratio = (x * 1.0) / original_width
        y = int(ratio * original_height)
    elif original_width > original_height and original_width > x:
        ratio = (y * 1.0) / original_height
        x = int(ratio * original_width)
    else:
        # No resize needed, use the original image.
        return mediafile.get_image_url()
        
    size = '%sx%s' % (x, y)
    log.info('Looking for %s thumbnail for %s (%s x %s)', size, mediafile.image, original_width, original_height)
    
    # defining the filename and the miniature filename
    filename = os.path.join(settings.MEDIA_ROOT, mediafile.image)
    filehead, filetail = os.path.split(filename)
    basename, format = os.path.splitext(filetail)
    miniature = basename + '_' + size + format
    miniature_filename = os.path.join(filehead, miniature)
    filehead, filetail = os.path.split(mediafile.get_image_url())
    miniature_url = filehead + '/' + miniature
    if os.path.exists(miniature_filename) and os.path.getmtime(filename)>os.path.getmtime(miniature_filename):
        os.unlink(miniature_filename)
    # if the image wasn't already resized, resize it
    if not os.path.exists(miniature_filename):
        image = Image.open(filename)
        image.thumbnail([x, y], Image.ANTIALIAS)
        try:
            image.save(miniature_filename, image.format, quality=90, optimize=1)
        except:
            image.save(miniature_filename, image.format, quality=90)

    return miniature_url

register.filter(thumbnail)